//
//  RTJAutoMarkLendController.m
//  RuiTaiJinProject
//
//  Created by jayson on 2019/1/10.
//  Copyright © 2019年 leewei. All rights reserved.
//

#import "RTJAutoMarkLendController.h"
#import "RTJLendCell.h"
#import "RTJChargeController.h"
#import "RTJUseRrealNameController.h"
#import "RTJRiskAssessmentController.h"
#import "RTJForgetPassWordController.h"
#import "SpecialAlertView.h"
#import "RTJAutoMarkTimeAlertView.h"
#import "LewPopupViewAnimationFade.h"
#import "RTJBidRecordsRootController.h"


@interface RTJAutoMarkLendController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,assign) BOOL isSelected;
@property (nonatomic,strong) NSString *money;
@property (nonatomic,strong) NSString *typeStr;
@property (nonatomic,strong) NSString *typeIdStr;

@property (nonatomic,strong) NSString *shouyiStr;
@property (nonatomic,assign) BOOL isSurePay;
@property (nonatomic,strong) NSArray *arr;

@end

@implementation RTJAutoMarkLendController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"立即出借";
    self.tableView.tableFooterView=[UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.estimatedRowHeight=300;
    _isSelected = YES;
    _typeStr = @"请选择";
    
    [self loadData];
    
}

-(void)loadData{
    
    [SVProgressHUD  showWithStatus:nil];
    [self.view showEmptyViewWithStr:@"" image:nil callback:nil];

    [RTJNetWork asyncRequestWithURL:@"deals/bid_plan" params:@{@"id":_idStr} method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [SVProgressHUD dismiss];
        [self.view removeEmptyView];

        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                self.arr = data[@"data"][@"loantype"];
                [self.tableView reloadData];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];
                [self.view showEmptyViewWithStr:data[@"msg"] image:[UIImage imageNamed:@"kbylogo"] callback:^{
                    
                    [self loadData];
                }];
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            [self.view showEmptyViewWithStr:errorMsg image:[UIImage imageNamed:@"kbylogo"] callback:^{
                
                [self loadData];
            }];
        }
        
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewAutomaticDimension;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * ID = @"RTJLendCell";
    
    RTJLendCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (!cell) {
        
        cell = [[NSBundle mainBundle] loadNibNamed:@"RTJLendCell" owner:self options:nil][5];
    }

    cell.autoTitle.text = _titleStr;
    
    if ([_max_mon isEqualToString:@"0.00"]) {
        
        cell.autoqitou.text = [NSString stringWithFormat:@"%@元起投",_min_mon];
//        cell.autoqitou.text = @"";

        
    }else{
        
        cell.autoqitou.text = [NSString stringWithFormat:@"投资上限金额%@元",_max_mon];
        
    }
    
    cell.autorate.text = _rateStr;
    
    
    if ([_rebateStr isEqualToString:@"0.00"]) {
        
        cell.autorate1.text = @"";
        
    }else{
        
        cell.autorate1.text = [NSString stringWithFormat:@"+%@%@",_rebateStr,@"%"];
    }
    
    cell.autotime.text = _timeStr;
    
    cell.autoText.delegate = self;
    cell.autoText.placeholder = [NSString stringWithFormat:@"%@元起投",_min_mon];

    cell.autoText.text = _money;
    
    cell.autoselectLab.text = _typeStr ;
    cell.autoselectLab.textColor = [_typeStr isEqualToString:@"请选择"] ? [UIColor colorForHex:@"#cccccc"] :[UIColor colorForHex:@"#666666"];
    
//    cell.autoshouyi.text =_shouyiStr.length!=0 ? [NSString stringWithFormat:@"%@元",_shouyiStr] :@"0元";
    
    cell.autokeyong.text = [NSString stringWithFormat:@"可用余额：%@ 元",[RTJUserTool getTheUserModel].money_format];
    cell.autoSelectBtn.selected = _isSelected;
    [cell.autoSelectBtn addTarget:self action:@selector(selectedBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell.typeBtn addTarget:self action:@selector(typeBtn) forControlEvents:UIControlEventTouchUpInside];
    [cell.autochongzhiBtn addTarget:self action:@selector(autochongzhiBtn) forControlEvents:UIControlEventTouchUpInside];
    [cell.xieyiBtn4 addTarget:self action:@selector(xieyi) forControlEvents:UIControlEventTouchUpInside];
    [cell.xieyiBtn5 addTarget:self action:@selector(xieyi1) forControlEvents:UIControlEventTouchUpInside];
    [cell.xieyiBtn6 addTarget:self action:@selector(xieyi2) forControlEvents:UIControlEventTouchUpInside];
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return  cell;
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    _money = textField.text;

    NSInteger shuruMoney = [_money integerValue];
    NSString *str = [_min_mon stringByReplacingOccurrencesOfString:@"," withString:@""];
    NSString *str1 = [_max_mon stringByReplacingOccurrencesOfString:@"," withString:@""];

    NSInteger min_mon = [str integerValue];
    NSInteger max_mon = [str1 integerValue];

    
    if (shuruMoney< min_mon) {
        
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@元起投,请重新输入金额",_min_mon]];
        _isSurePay = YES;
        
        CGFloat rete = [_rateStr floatValue];
        CGFloat rebate1 = [_rebateStr floatValue];//加息
        CGFloat repay_time = [_timeStr floatValue];
        
        CGFloat shouyi = shuruMoney*((rete+rebate1)/100/12)*repay_time;
        
        _shouyiStr = [NSString stringWithFormat:@"%.2f",shouyi];
        
        [self.tableView reloadData];
        
        return;
        
        
    }else if (shuruMoney>max_mon&& max_mon!=0){
        
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"超过投资上限%@元,请重新输入金额",_max_mon]];
 
        _isSurePay = YES;
        
        CGFloat rete = [_rateStr floatValue];
        CGFloat rebate1 = [_rebateStr floatValue];//加息
        CGFloat repay_time = [_timeStr floatValue];
        
        CGFloat shouyi = shuruMoney*((rete+rebate1)/100/12)*repay_time;
        
        _shouyiStr = [NSString stringWithFormat:@"%.2f",shouyi];
        
        [self.tableView reloadData];
        
        return;
        
    }else{
        
//        账户剩余的钱
        NSInteger money = [[RTJUserTool getTheUserModel].money integerValue];
        
        if (shuruMoney>money) {
            
            [SVProgressHUD showErrorWithStatus:@"账户余额不足，请前往充值"];
            _isSurePay = YES;
            return;
        }
        
        //预期收益
        //收益 = 投标金额*（预期年化*/100/12）*投资期限
        CGFloat rebate1 = [_rebateStr floatValue];//加息
        
        CGFloat rete = [_rateStr floatValue];
        
        CGFloat repay_time = [_timeStr floatValue];
        
        CGFloat shouyi = shuruMoney*((rete+rebate1)/100/12)*repay_time;
        
        _shouyiStr = [NSString stringWithFormat:@"%.2f",shouyi];
        
        _isSurePay = NO;
        
        [self.tableView reloadData];
        
    }
    
}

-(void)typeBtn{
    
    RTJAutoMarkTimeAlertView *view = [RTJAutoMarkTimeAlertView defaultPopupViewWithFrame:CGRectMake(0, 0,350, 265) isPayWay:YES array:_arr];
    view.parentVC = self;
    
    [self lew_presentPopupView:view animation:[LewPopupViewAnimationFade new] dismissed:^{
        
        NSLog(@"动画结束");
        
    }];
    
    [view withMonthSureClick:^(NSMutableArray * _Nonnull monthArr) {
        
        NSMutableArray *arrs = [NSMutableArray array];
        NSMutableArray *arrId = [NSMutableArray array];

        for (NSDictionary *dic in monthArr) {
            
            for (NSDictionary *dict in self.arr) {
                
                if ([dict [@"value"] isEqualToString:dic[@"value"]]) {
                    
                    [arrs addObject:dict [@"name"]];
                    [arrId addObject:dict [@"value"]];

                }
            }
        }
        
        self.typeStr = [arrs componentsJoinedByString:@","];
        self.typeIdStr = [arrId componentsJoinedByString:@","];
        [self.tableView reloadData];
        
    }];
    
}

-(void)selectedBtn:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    _isSelected = btn.selected;
    
}

-(void)autochongzhiBtn{
    
    //充值
    RTJChargeController *VC = [[RTJChargeController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
    
}

-(void)xieyi{
    
    [self loadUrl:@"fengxianjiesishu" title:@"风险揭示书"];
    
}

-(void)xieyi2{
    
    [self loadUrl:@"dianziqianzhang" title:@"电子签章授权委托书"];

}

-(void)xieyi1{
    
    [self loadUrl:@"loan_agreement" title:@"瑞泰金借款协议"];
    
}

-(void)loadUrl:(NSString *)url title:(NSString *)title{
    
    RTJHTMLViewController *vc = [[RTJHTMLViewController alloc]init];
    vc.title = title;
    vc.htmlStr = url;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (IBAction)lendout:(id)sender {

    if (_isSelected == NO) {
        
        [SVProgressHUD showErrorWithStatus:@"请仔细阅读相关协议"];
        return;
    }

    if (_money.length==0) {
        
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@元起投,请重新输入金额",_min_mon]];
        return;
    }
    
    if ([RTJUserTool getTheUserModel].idcardpassed == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"你还没有进行实名认证，请前往认证"];
        
        RTJUseRrealNameController *vc = [[RTJUseRrealNameController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    
    if ([RTJUserTool getTheUserModel].is_risk == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"你还没有进行风险评测，请前往测评"];
        
        RTJRiskAssessmentController *risk =  [[RTJRiskAssessmentController alloc]init];
        [self.navigationController pushViewController:risk animated:YES];
        return;
        
    }
    
    NSString *paypassword = [RTJUserTool getTheUserModel].paypassword;
    
    if ( paypassword.length ==0) {
        
        [SVProgressHUD showErrorWithStatus:@"你还没有设置交易密码，请前往设置"];
        RTJForgetPassWordController *vc = [[RTJForgetPassWordController alloc]init];
        vc.title = @"设置支付密码";
        vc.isPayPassWord = YES;
        vc.isForgetPassWord = NO;
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
        
    }
    
    if (_typeIdStr.length==0) {
        
        [SVProgressHUD showErrorWithStatus:@"请选择还款方式"];
        return;
    }
    
    SpecialAlertView *special = [[SpecialAlertView alloc]initWithLevelType:YES];
    
    [special withSureClick:^(NSInteger tags,NSString *password,UIView *alertView) {
        
        [UIView animateWithDuration:0.3 animations:^{
            [alertView removeFromSuperview];
        }];
        
        if (tags == 110) {
            
//            [UIView animateWithDuration:0.3 animations:^{
//                [alertView removeFromSuperview];
//            }];
            
            RTJForgetPassWordController *vc = [[RTJForgetPassWordController alloc]init];
            vc.isPayPassWord = YES;
            vc.title = @"找回支付密码";
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            
            if (password.length  == 0) {
                
                [SVProgressHUD showErrorWithStatus:@"请输入交易密码"];
                return ;
            }
            //验证支付密码是否正确
            [RTJNetWork asyncRequestWithURL:@"user/check_pay_password" params:@{@"pay_password":password} method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
                
                if (success) {
                    
                    if ([data[@"status"]integerValue]==1) {
                        
                        //开始进行投标支付
                        [self bidPaymentImmediately:password];
                        
                    }else{
                        
                        
                        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"密码错误:%@",data[@"msg"]]];
                    }
                    
                }else{
                    
                    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"密码错误:%@",errorMsg]];
                    
                }
                
            }];
            
        }
        
    }];
}

-(void)bidPaymentImmediately:(NSString *)password{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"id":_idStr,
                                                                               @"money":_money,
                                                                               @"paypassword":password,
                                                                               @"loantype":_typeIdStr
                                                                               }];
   
    
    [RTJNetWork asyncRequestWithURL:@"deals/dobid_plan" params:dic method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        if (success) {
            
            if ([data[@"status"]integerValue]==1) {
                
                [SVProgressHUD showSuccessWithStatus:@"投标成功"];
                RTJBidRecordsRootController *vc = [[RTJBidRecordsRootController alloc]init];
                vc.isAuto = YES;
                [self.navigationController pushViewController:vc animated:YES];
                
            }else{
                
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"投标失败:%@",data[@"msg"]]];
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            
        }
    }];
    
}

@end
